package asapIs134CK.womi.server.profile;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.Query;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import com.google.gwt.user.server.rpc.RemoteServiceServlet;

import asapIs134CK.womi.client.profile.RPCUserService;
import asapIs134CK.womi.client.profile.UserClient;
import asapIs134CK.womi.server.EMF;

public class RPCUserServiceImpl extends RemoteServiceServlet implements RPCUserService{

	public boolean addUser(UserClient user) {
		boolean res = false;
		String md5 = md5(user.getMd5Pwd());
	    user.setMd5pwd(md5);
	    System.out.println(md5);
	    EntityManager em = EMF.get().createEntityManager();
	    try {
	    	UserServer usr = new UserServer(user);
	        em.persist(usr);
	        res = true;
	    } finally {
	        em.close();
	    }
		return res;
	}

	public List getAll() {
		List tmp = null;
		List res = null;
	    EntityManager em = EMF.get().createEntityManager();
	    try {
	    	Query query = em.createQuery("SELECT u FROM UserServer u");
	    	tmp = query.getResultList();
	    	res = new ArrayList();
	    	Iterator ite = tmp.iterator();
	    	while(ite.hasNext()){
	    		UserServer o = (UserServer) ite.next();
	    		UserClient u = cloneUserServerToUserClient(o);
	    		res.add(u);
	    	}
	    } finally {
	        em.close();
	    }
		return res;
	}

	public UserClient authenticateUser(String email, String md5pwd) {
	    EntityManager em = EMF.get().createEntityManager();
		String md5 = md5(md5pwd);
	    UserClient res = null;
	    try {
	    	javax.persistence.Query query = em.createQuery("SELECT FROM UserServer WHERE _email = :email");
	    	query.setParameter("email", email);
	        List<UserServer> users = query.getResultList();
	        UserServer user = null;
	        if(users.size()==1){
	        	user = users.get(0);
	        }
	        if(user != null && user.getMd5Pwd().equals(md5)){
	        	res = cloneUserServerToUserClient(user);
	        	addUserToSession(res);
	        }
	    } finally {
	        em.close();
	    }
		return res;
	}

	public boolean modifyUser(UserClient user) {
		boolean res = false;
	    EntityManager em = EMF.get().createEntityManager();
	    try {
	    	Query query = em.createQuery("SELECT FROM UserServer WHERE _email = :email");
	    	query.setParameter("email", user.getEmail());
	    	UserServer usr = (UserServer) query.getResultList().get(0);
	    	usr.clone(user);
	        em.merge(usr);

	    	HttpServletRequest request = this.getThreadLocalRequest();
	    	HttpSession session = request.getSession();
	    	Object o = session.getAttribute("UserWomi");
	    	if(o!=null && ((UserClient)o).getEmail().equals(user.getEmail())){
	    		session.setAttribute("UserWomi", user);
	    	}
	       
	    	res = true;
	    } finally {
	        em.close();
	    }
		return res;
	}
	
	private UserClient cloneUserServerToUserClient(UserServer user){
		UserClient res = new UserClient(user.getNickname(), user.getEmail(),user.getAvatar(), "");
		res.setScoreArithmeticQuizz(user.getScoreArithmeticQuizz());
		res.setAdmin(user.isAdmin());
		res.setTestCreator(user.isTestCreator());
		res.setScoreFroggit(user.getScoreFroggit());
		res.setScoreSudoku(user.getScoreSudoku());
		return res;
	}
	
	private void addUserToSession(UserClient usr){
    	HttpServletRequest request = this.getThreadLocalRequest();
    	HttpSession session = request.getSession();
    	session.setAttribute("UserWomi", usr);
	}
	
	private String md5(String value){
		String res="";
		MessageDigest digest;
		try {
			digest = java.security.MessageDigest.getInstance("md5");
		    digest.digest(value.getBytes());
		    byte[] hash = digest.digest();
		    res = new String(hash);
		} catch (NoSuchAlgorithmException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return res;
	}
	
	@Override
	public UserClient getCurrentUser() {
    	HttpServletRequest request = this.getThreadLocalRequest();
    	HttpSession session = request.getSession();
    	Object o = session.getAttribute("UserWomi");
    	UserClient res = null;
    	if(o != null){
    		res = (UserClient) o;
    	}
		return res;
	}

}
